<?php
declare(strict_types=1);
namespace App\Controller\Api\V1;

use App\Controller\Api\BaseController;
use App\Factory\WechatFactory;
use App\Repositories\UserRepository;
use App\Repositories\UserWechatRepository;
use App\Request\LoginByPhoneRequest;
use App\Services\UserService;
use Hyperf\Di\Annotation\Inject;
use Phper666\JwtAuth\Jwt;

class AuthController extends BaseController
{
    /**
     * @Inject
     * @var UserService
     */
    private $service;

    /**
     * @Inject
     * @var WechatFactory
     */
    private $wechatFactory;

    /**
     * @param LoginByPhoneRequest $request
     * @return \Psr\Http\Message\ResponseInterface
     */

    public function loginByPhone(LoginByPhoneRequest $request)
    {
        $data = $request->all();
        $return = $this->service->quickLogin($data);
        if(!$return['success']){
            return $this->response->error(10013,$return['msg']);
        }
        return $this->response->success($return['data']);
    }

    public function wechatCheckUser(){
        $data = $this->request->all();
        $app = $this->wechatFactory->create();
        $session = $app->auth->session($data['code']);
        if(isset($session['errcode'])&&$session['errcode']!=0){
            return $this->response->error($session['errcode'],$session['errmsg']);
        }
        $openid = $session['openid'];
        $user_wechat = UserWechatRepository::getInstance()->one(['id','user_id'],[[
            'field' => 'wx_openid',
            'value' => $openid
        ]]);
        if(!$user_wechat){
            return $this->response->success(['user_id'=>0]);
        }
        $result = $this->service->loginByUserId($user_wechat->user_id);
        return $this->response->success($result['data']);
    }

    public function loginByWechat()
    {
        $data = $this->request->all();
        $app = $this->wechatFactory->create();
        $session = $app->auth->session($data['code']);
        if(isset($session['errcode'])&&$session['errcode']!=0){
            return $this->response->error($session['errcode'],$session['errmsg']);
        }
        $data['wx_openid'] = $session['openid'];
        //查询是否存在
        $user_wechat = UserWechatRepository::getInstance()->one(['id','user_id'],[[
            'field' => 'wx_openid',
            'value' => $data['wx_openid']
        ]]);
        if($user_wechat){
            $user = UserRepository::getInstance()->one(['id','mobile'],[[
                'field' => 'id',
                'value' => $user_wechat->user_id
            ]]);
            $data['mobile'] = $user->mobile;
        }else{
            $userInfo = $app->encryptor->decryptData($session['session_key'], $data['iv'], $data['encryptedData']);
            $data['mobile'] = $userInfo['phoneNumber'];
        }
        $return  = $this->service->wechatLogin($data);
        return $this->response->success($return['data']);
    }

    public function loginByAuthorization()
    {
        $data = $this->request->all();
        $app = $this->wechatFactory->create();
        $session = $app->auth->session($data['code']);
        $data['wx_openid'] = $session['openid'];
        $return  = $this->service->wechatByOpenidLogin($data);
        return $this->response->success($return['data']);
    }

    public function userSync(){
        $data = $this->request->all();
        $return  = $this->service->userSync($data);
        return $this->response->success($return['data']);
    }

    public function loginByWechatTest()
    {
        $data = $this->request->all();
        $data['mobile'] = '18669387024';
        $data['wx_openid'] = 'wxdfasdfdsafdsafdsfdas';
        $return  = $this->service->wechatLogin($data);
        return $this->response->success($return['data']);
    }

    public function refreshToken()
    {
        $return  = $this->service->refreshToken();
        if($return['success']){
            return $this->response->success($return['data']);
        }
        return $this->response->error(10010,$return['msg']);
    }

    public function bindPhone()
    {
        $user = $this->request->getAttribute('user');
        $data = $this->request->all();
        $app = $this->wechatFactory->create();
        $session = $app->auth->session($data['code']);
        $userInfo = $app->encryptor->decryptData($session['session_key'], $data['iv'], $data['encryptedData']);
        $data['mobile'] = $userInfo['phoneNumber'];
        try{
            $user->mobile = $data['mobile'];
            if(!$user->save()){
                throw new \Exception('绑定手机号失败');
            }
        }catch(\Throwable $exception){
            return $this->response->error(10010,$exception->getMessage());
        }
        //执行绑定手机号任务
        //$this->task_service->doTask('bind_phone',$user);
        return $this->response->success($data);
    }

    public function bindPhoneTest()
    {
        $user = $this->request->getAttribute('user');
        $data['mobile'] = '18669387024';
        try{
            $user->mobile = $data['mobile'];
            if(!$user->save()){
                throw new \Exception('绑定手机号失败');
            }
        }catch(\Throwable $exception){
            return $this->response->error(10010,$exception->getMessage());
        }
        //执行绑定手机号任务
        //$this->task_service->doTask('bind_phone',$user);
        return $this->response->success($data);
    }

    public function sendCode()
    {

    }
}